<template>
	<view class="container">
		<!-- 顶部导航栏 -->
		<view class="header">
			<text class="title">{{ viewType === 'orgChart' ? '组织架构图' : '项目管理' }}</text>
		</view>

		<!-- 操作按钮区 -->
		<view class="toolbar">
			<button type="primary" class="add-btn" @click="addNode">添加节点</button>
			<button type="default" class="delete-btn" @click="deleteNode" :disabled="!currentNode">删除节点</button>
			<button type="default" class="edit-btn" @click="editNode" :disabled="!currentNode">编辑节点</button>
			<!-- 新增切换视图按钮 -->
			<button type="default" class="switch-btn" @click="switchView">切换视图</button>
		</view>

		<!-- 根据视图类型渲染不同内容 -->
		<view v-if="viewType === 'orgChart'" class="org-chart-container" @touchstart="dragStart" @touchmove="dragMove"
			@touchend="dragEnd">
			<!-- Canvas 用于绘制连接线 -->
			<canvas class="org-chart-canvas" canvas-id="orgChartCanvas"></canvas>

			<!-- 节点和文本（在Canvas之上） -->
			<view class="org-chart-nodes" :style="{transform: `translate(${dragX}px, ${dragY}px)`}">
				<template v-for="(node, index) in flattenedNodes" :key="node.id">
					<view class="org-node" :style="{left: `${node.x}px`, top: `${node.y}px`}"
						@touchstart="nodeDragStart(node, $event)" @touchmove="nodeDragMove(node, $event)"
						@touchend="nodeDragEnd" @click="selectNode(node, $event)">
						<text>{{ node.role }}</text>
					</view>
					<text class="node-text" :style="{left: `${node.x}px`, top: `${node.y + nodeSize * 2}px`}">
						{{ node.name }}
					</text>
				</template>
			</view>
		</view>

		<view v-else class="project-management-container">
			<!-- 项目管理列表视图 -->
			<view class="project-item" v-for="(project, projectIndex) in projectData" :key="project.id">
				<view class="project-info">
					<text class="project-title">项目{{ projectIndex + 1 }}</text>
					<text>负责人：{{ project.leader }}</text>
					<text>状态：{{ project.status }}</text>
					<button type="default" @click="toggleSubProjects(project)">展开项目</button>
				</view>
				<view class="sub-projects" v-show="project.showSub">
					<view class="sub-project-item" v-for="(subProject, subIndex) in project.children"
						:key="subProject.id">
						<text>子项目{{ subIndex + 1 }}</text>
						<text>负责人：{{ subProject.leader }}</text>
						<text>状态：{{ subProject.status }}</text>
						<button type="default" @click="viewSubContent(subProject)">查看内容</button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				viewType: 'orgChart', // 初始为组织架构图视图，可选值 'orgChart' | 'projectManagement'
				currentNode: null,
				// 拖拽相关
				dragX: 0,
				dragY: 0,
				startX: 0,
				startY: 0,
				isDragging: false,
				isNodeDragging: false,
				draggingNode: null,
				nodeStartX: 0,
				nodeStartY: 0,
				// 组织数据（原组织架构数据，可用于切换回组织架构图时展示）
				orgData: {
					id: 'root',
					role: "项目经理",
					name: "负责人姓名",
					x: 0,
					y: 0,
					children: [{
							id: 'manager1',
							role: "队长",
							name: "负责人姓名",
							x: 0,
							y: 0,
							children: [{
								id: 'staff1',
								role: "队员",
								name: "负责人姓名",
								x: 0,
								y: 0,
							}]
						},
						{
							id: 'manager2',
							role: "队长",
							name: "负责人姓名",
							x: 0,
							y: 0,
							children: [{
								id: 'staff2',
								role: "队员",
								name: "负责人姓名",
								x: 0,
								y: 0,
							}]
						}
					]
				},
				// 项目管理列表数据（模拟，可根据实际从 orgData 转换或接口获取）
				projectData: [{
						id: 'project1',
						leader: '负责人1',
						status: '进行中',
						children: [{
								id: 'sub1',
								leader: '子负责人1',
								status: '进行中'
							},
							{
								id: 'sub2',
								leader: '子负责人2',
								status: '未开始'
							},
							{
								id: 'sub3',
								leader: '子负责人3',
								status: '已完成'
							}
						],
						showSub: false
					},
					{
						id: 'project2',
						leader: '负责人2',
						status: '未开始',
						children: [],
						showSub: false
					}
				],
				// Canvas 上下文
				ctx: null,
				// 画布尺寸
				canvasWidth: 750,
				canvasHeight: 1000,
				// 扩展画布尺寸（增加边距）
				extendedWidth: 0,
				extendedHeight: 0,
				// 节点尺寸（使用px单位，与CSS中rpx对应）
				nodeSize: 80, // 对应CSS中的160rpx（假设750rpx=375px）
				// rpx到px的转换比例
				rpxRatio: 0.5 // 默认750rpx=375px
			};
		},
		computed: {
			// 扁平化的节点数组（组织架构图用）
			flattenedNodes() {
				const nodes = [];

				function flatten(node) {
					nodes.push(node);
					if (node.children && node.children.length > 0) {
						node.children.forEach(child => flatten(child));
					}
				}
				flatten(this.orgData);
				return nodes;
			},
			// 连接线计算（应用拖拽，组织架构图用）
			connectors() {
				const connectors = [];
				let connectorId = 0;

				function createConnectors(parent, children) {
					if (!children || children.length === 0) return;
					children.forEach(child => {
						// 创建带转折点的连接线
						const midX = (parent.x + this.nodeSize + child.x + this.nodeSize) / 2;
						const midY = parent.y + this.nodeSize + 50; // 转折点在父节点下方50px处
						connectors.push({
							id: `connector-${connectorId++}`,
							parentId: parent.id,
							childId: child.id,
							x1: parent.x + this.nodeSize, // 父节点圆心x
							y1: parent.y + this.nodeSize, // 父节点圆心y
							x2: midX,
							y2: midY,
							x3: midX,
							y3: child.y + this.nodeSize - 30, // 转折点到子节点上方30px处
							x4: child.x + this.nodeSize, // 子节点圆心x
							y4: child.y + this.nodeSize // 子节点圆心y
						});
						if (child.children && child.children.length > 0) {
							createConnectors.call(this, child, child.children);
						}
					});
				}
				createConnectors.call(this, this.orgData, this.orgData.children);
				return connectors;
			}
		},
		mounted() {
			if (this.viewType === 'orgChart') {
				// 获取Canvas上下文（组织架构图时初始化）
				this.ctx = uni.createCanvasContext('orgChartCanvas', this);
				// 获取画布尺寸
				const query = uni.createSelectorQuery().in(this);
				query.select('.org-chart-canvas').boundingClientRect(rect => {
					this.canvasWidth = rect.width;
					this.canvasHeight = rect.height;
					// 计算rpx到px的转换比例
					this.rpxRatio = rect.width / 750;
					// 更新节点尺寸
					this.nodeSize = 160 * this.rpxRatio / 2;
					// 扩展画布尺寸（增加50%边距）
					this.extendedWidth = this.canvasWidth * 1.5;
					this.extendedHeight = this.canvasHeight * 1.5;
					// 计算布局参数
					this.calculateLayout();
					// 初始绘制连接线
					this.drawConnectors();
				}).exec();
			}
		},
		watch: {
			// 监听节点位置变化，重新绘制连接线（组织架构图用）
			flattenedNodes: {
				deep: true,
				handler() {
					if (this.viewType === 'orgChart') {
						this.drawConnectors();
					}
				}
			},
			// 监听拖拽变化，重新绘制连接线（组织架构图用）
			dragX() {
				if (this.viewType === 'orgChart') {
					this.drawConnectors();
				}
			},
			dragY() {
				if (this.viewType === 'orgChart') {
					this.drawConnectors();
				}
			}
		},
		methods: {
			// 切换视图方法
			switchView() {
				this.viewType = this.viewType === 'orgChart' ? 'projectManagement' : 'orgChart';
				if (this.viewType === 'orgChart') {
					// 切换回组织架构图时重新初始化Canvas相关
					this.ctx = uni.createCanvasContext('orgChartCanvas', this);
					const query = uni.createSelectorQuery().in(this);
					query.select('.org-chart-canvas').boundingClientRect(rect => {
						this.canvasWidth = rect.width;
						this.canvasHeight = rect.height;
						this.rpxRatio = rect.width / 750;
						this.nodeSize = 160 * this.rpxRatio / 2;
						this.extendedWidth = this.canvasWidth * 1.5;
						this.extendedHeight = this.canvasHeight * 1.5;
						this.calculateLayout();
						this.drawConnectors();
					}).exec();
				}
			},
			// 计算节点布局（组织架构图用）
			calculateLayout() {
				// 以最顶层为原点，计算节点位置
				const padding = 100 * this.rpxRatio; // 边距，转换为px
				// 根节点位置（扩展画布中心）
				this.orgData.x = (this.extendedWidth - this.nodeSize * 2) / 2;
				this.orgData.y = padding;
				// 计算子节点位置
				const level1Nodes = this.orgData.children;
				const level1Count = level1Nodes.length;
				const level1Spacing = (this.extendedWidth - 2 * padding) / (level1Count + 1);
				level1Nodes.forEach((node, index) => {
					// 水平位置均匀分布
					node.x = padding + level1Spacing * (index + 1) - this.nodeSize;
					// 垂直位置在根节点下方
					node.y = this.orgData.y + 200 * this.rpxRatio;
					// 计算二级子节点位置
					const level2Nodes = node.children;
					if (level2Nodes && level2Nodes.length > 0) {
						const level2Count = level2Nodes.length;
						const level2Spacing = level1Spacing / (level2Count + 1);
						level2Nodes.forEach((child, childIndex) => {
							// 水平位置相对于父节点均匀分布
							child.x = node.x - level1Spacing / 2 + level2Spacing * (childIndex + 1);
							// 垂直位置在父节点下方
							child.y = node.y + 200 * this.rpxRatio;
						});
					}
				});
			},
			// 绘制连接线（组织架构图用）
			drawConnectors() {
				if (this.viewType !== 'orgChart') return;
				// 清空Canvas
				this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
				// 绘制所有连接线，不应用整体变换，单独计算每个连接线的变换
				this.connectors.forEach(connector => {
					this.ctx.beginPath();
					// 计算连接线的起点和终点（考虑拖拽）
					const x1 = connector.x1 + this.dragX;
					const y1 = connector.y1 + this.dragY;
					const x2 = connector.x2 + this.dragX;
					const y2 = connector.y2 + this.dragY;
					const x3 = connector.x3 + this.dragX;
					const y3 = connector.y3 + this.dragY;
					const x4 = connector.x4 + this.dragX;
					const y4 = connector.y4 + this.dragY;
					// 绘制带转折点的连接线
					this.ctx.moveTo(x1, y1);
					this.ctx.lineTo(x2, y2);
					this.ctx.lineTo(x3, y3);
					this.ctx.lineTo(x4, y4);
					this.ctx.setStrokeStyle('#FF0000'); // 红色线条
					this.ctx.setLineWidth(4); // 保持线条粗细一致
					this.ctx.stroke();
				});
				// 执行绘制
				this.ctx.draw();
			},
			// 节点选择（组织架构图用）
			selectNode(node, event) {
				if (this.isNodeDragging || this.viewType !== 'orgChart') return;
				// 使用uni-app的选择器API代替document.querySelectorAll
				uni.createSelectorQuery().in(this).selectAll('.org-node').boundingClientRect(rects => {
					rects.forEach((rect, index) => {
						rect.node.classList.remove('selected');
					});
				}).exec();
				event.currentTarget.classList.add('selected');
				this.currentNode = node.id;
			},
			// 整体画布拖拽开始（组织架构图用）
			dragStart(e) {
				if (this.viewType !== 'orgChart') return;
				if (this.isElementInContainer(e.target, '.org-node')) {
					return;
				}
				this.isDragging = true;
				this.startX = e.touches[0].clientX - this.dragX;
				this.startY = e.touches[0].clientY - this.dragY;
			},
			// 整体画布拖拽移动（组织架构图用）
			dragMove(e) {
				if (this.viewType !== 'orgChart' || !this.isDragging || this.isNodeDragging) return;
				// 计算新的拖拽位置
				this.dragX = e.touches[0].clientX - this.startX;
				this.dragY = e.touches[0].clientY - this.startY;
				// 拖拽时重新绘制连接线
				this.drawConnectors();
			},
			// 整体画布拖拽结束（组织架构图用）
			dragEnd() {
				if (this.viewType !== 'orgChart') return;
				this.isDragging = false;
			},
			// 节点拖拽开始 - 禁止根节点拖拽（组织架构图用）
			nodeDragStart(node, e) {
				if (this.viewType !== 'orgChart') return;
				e.stopPropagation();
				if (this.isElementInContainer(e.target, '.node-text') || node.id === 'root') {
					return;
				}
				this.isNodeDragging = true;
				this.draggingNode = node;
				// 计算相对于节点中心的偏移
				this.nodeStartX = e.touches[0].clientX - this.dragX - (node.x + this.nodeSize);
				this.nodeStartY = e.touches[0].clientY - this.dragY - (node.y + this.nodeSize);
			},
			// 节点拖拽移动（组织架构图用）
			nodeDragMove(node, e) {
				if (this.viewType !== 'orgChart' || !this.isNodeDragging || this.draggingNode.id !== node.id) return;
				// 计算节点新位置（考虑拖拽）
				node.x = e.touches[0].clientX - this.dragX - this.nodeStartX - this.nodeSize;
				node.y = e.touches[0].clientY - this.dragY - this.nodeStartY - this.nodeSize;
				// 使用扩展画布尺寸限制节点拖拽范围
				const maxX = this.extendedWidth - this.nodeSize * 2;
				const maxY = this.extendedHeight - this.nodeSize * 3; // 减去文本高度
				node.x = Math.max(Math.min(node.x, maxX), 0);
				node.y = Math.max(Math.min(node.y, maxY), 0);
				// 节点移动时重新绘制连接线
				this.drawConnectors();
			},
			// 节点拖拽结束（组织架构图用）
			nodeDragEnd() {
				if (this.viewType !== 'orgChart') return;
				this.isNodeDragging = false;
				this.draggingNode = null;
			},
			// 增删改方法（这里仅简单提示，实际需完善）
			addNode() {
				uni.showToast({
					title: '添加节点功能待实现',
					icon: 'none'
				});
			},
			deleteNode() {
				if (!this.currentNode || this.currentNode === 'root') {
					uni.showToast({
						title: '不能删除根节点',
						icon: 'none'
					});
					return;
				}
				uni.showToast({
					title: '删除节点功能待实现',
					icon: 'none'
				});
			},
			editNode() {
				if (!this.currentNode) return;
				uni.showToast({
					title: '编辑节点功能待实现',
					icon: 'none'
				});
			},
			// 切换项目子项展开/收起（项目管理视图用）
			toggleSubProjects(project) {
				project.showSub = !project.showSub;
			},
			// 查看子项目内容（项目管理视图用，仅示例，实际可跳转或展示详情）
			// 查看子项目内容（项目管理视图用，跳转详情页并传参）
			viewSubContent(subProject) {
				// 极端情况处理：如果 subProject 为空，直接提示
				if (!subProject) {
					uni.showToast({
						title: "没有可查看的项目数据",
						icon: "none"
					});
					return;
				}
				// 正确序列化并编码
				const projectStr = JSON.stringify(subProject);
				const encodedProject = encodeURIComponent(projectStr);
				// 跳转
				uni.navigateTo({
					url: `/pages/projectDetail/index?project=${encodedProject}`
				});
			},
			// 辅助方法：判断元素是否在指定容器内
			isElementInContainer(element, containerSelector) {
				let currentElement = element;
				while (currentElement) {
					if (currentElement.classList && currentElement.classList.contains(containerSelector.replace('.',
							''))) {
						return true;
					}
					currentElement = currentElement.parentElement;
					if (!currentElement || currentElement.classList.contains('org-chart-container')) {
						break;
					}
				}
				return false;
			}
		}
	};
</script>

<style scoped>
	.container {
		height: 100vh;
		display: flex;
		flex-direction: column;
	}

	.header {
		height: 88rpx;
		background: #007AFF;
		color: white;
		text-align: center;
		line-height: 88rpx;
	}

	.toolbar {
		padding: 20rpx;
		display: flex;
		justify-content: space-around;
	}

	.add-btn {
		background-color: #4CD964;
	}

	.switch-btn {
		background-color: #586BFF;
		color: white;
	}

	/* 组织架构图相关样式 */
	.org-chart-container {
		flex: 1;
		overflow: hidden;
		position: relative;
		touch-action: none;
	}

	.org-chart-canvas {
		position: absolute;
		width: 100%;
		height: 100%;
		top: 0;
		left: 0;
		z-index: 1;
	}

	.org-chart-nodes {
		position: absolute;
		width: 100%;
		height: 100%;
		top: 0;
		left: 0;
		z-index: 2;
	}

	.org-node {
		width: 160rpx;
		height: 160rpx;
		border-radius: 50%;
		background-color: white;
		border: 1px solid #cccccc;
		display: flex;
		align-items: center;
		justify-content: center;
		position: absolute;
		z-index: 5;
		box-sizing: border-box;
		cursor: move;
		transition: all 0.2s ease;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}

	.org-node.selected {
		border: 2px solid #007AFF;
		box-shadow: 0 0 10rpx rgba(0, 122, 255, 0.5);
	}

	.org-node text {
		font-size: 28rpx;
		text-align: center;
		color: #333;
	}

	.node-text {
		position: absolute;
		font-size: 24rpx;
		color: #666;
		text-align: center;
		width: 160rpx;
	}

	/* 项目管理视图相关样式 */
	.project-management-container {
		flex: 1;
		overflow-y: auto;
		padding: 20rpx;
		background-color: #f7f7f7;
	}

	.project-item {
		background-color: white;
		border-radius: 12rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
		overflow: hidden;
	}

	.project-info {
		padding: 20rpx;
		display: flex;
		flex-direction: column;
		gap: 10rpx;
		border-bottom: 1rpx solid #eee;
	}

	.project-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.sub-projects {
		padding: 20rpx;
		background-color: #fcfcfc;
	}

	.sub-project-item {
		padding: 15rpx 0;
		border-bottom: 1rpx solid #f0f0f0;
		display: flex;
		flex-direction: column;
		gap: 8rpx;
	}

	.sub-project-item:last-child {
		border-bottom: none;
	}

	button {
		border-radius: 8rpx;
		font-size: 24rpx;
		padding: 10rpx 20rpx;
		min-width: 160rpx;
	}
</style>